home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 80 / CD Actual 80 Julio-Agosto 2003.iso / Linux / LinuxGazette / lg / issue39 / rogers_example05c.c < prev    next >
Encoding:
C/C++ Source or Header  |  2002-08-14  |  1.4 KB  |  66 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /*
  5.  
  6.     This program is written to demonstrate the <stdlib.h> library.
  7.  
  8.     This program will demonstrate seaching and sorting and random numbers
  9.  
  10.     Written by James M. Rogers
  11.  
  12.     17 March 1999
  13.  
  14.     Released to the Public Domain on this date.
  15.  
  16. */
  17.  
  18. #define ELEMENTS 50000
  19.  
  20. /* this is the compare program that we call with qsort to sort the array */
  21. static int compar(const void *a, const void *b){
  22.     return (strcmp( (char *)a, (char *)b));
  23. }
  24.  
  25. main(){
  26.  
  27.     int x, i;
  28.     char *string;
  29.     struct sort_test_t {
  30.         char s[16];
  31.     } ;
  32.  
  33.     struct sort_test_t sort_test[ELEMENTS];
  34.  
  35.     /* initalize the pseudo-random sequence with the time */
  36.     /* if you remove the following command then the program */
  37.     /* will generate the same series of "random" numbers each */
  38.     /* time the program is ran */
  39.     srand(time());
  40.  
  41.     /* inititalize the array */
  42.     for (i=0;i<ELEMENTS;i++) {
  43.         /* produce a random variable */
  44.         x=1+(100000.0*rand()/(RAND_MAX+1.0));
  45.         /* load the variable into the string as an array */
  46.         sprintf(sort_test[i].s,"%d\000", x);
  47.     }
  48.  
  49.     /* sort the array */
  50.     qsort(sort_test, ELEMENTS, sizeof(sort_test[0]), &compar);
  51.  
  52.     /* seach the array */
  53.  
  54.     if (string = bsearch("1000", sort_test, ELEMENTS, sizeof(sort_test[0]), &compar)) {
  55.         printf("The string 1000 is present.\n");
  56.     } else {
  57.         printf("The string 1000 is not present!\n");
  58.     }
  59.  
  60.     /* output the sorted array */
  61.     for (i=0;i<ELEMENTS;i++) {
  62.         printf("%d %s\n", i, sort_test[i].s);
  63.     }
  64.  
  65. }
  66.